import { loginAPI, getUserInfoAPI } from '@/api'

export default {
  namespaced: true,
  state: {
    token: '',
    userId: '',
    userInfo: null,
    tokenTime: ''
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    removeToken(state) {
      state.token = null
    },
    setUserId(state, userId) {
      state.userId = userId
    },
    removeUserId(state) {
      state.userId = null
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = null
    },
    setTokenTime(state, time) {
      state.tokenTime = time
    }

  },
  actions: {
    async loginAction({ commit }, data) {
      const res = await loginAPI(data)
      console.log(res)
      commit('setToken', res.data.token)
      commit('setUserId', res.data.userId)
      commit('setTokenTime', Date.now())
    },
    async getUserInfo({ state, commit }) {
      const { data } = await getUserInfoAPI(state.userId)
      console.log(data)
      commit('setUserInfo', data)
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      commit('removeUserId')
    }

  }
}
